package com.itic.appbase.framework.utils;

import net.sf.json.JSONObject;
import org.apache.http.HttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.util.EntityUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.net.URL;
import java.net.URLConnection;
import java.net.URLDecoder;

public class HttpRequestUtils {
	
	//
	////发送 GET 请求
   // 
    
    //发送 POST 请求
   //String sr=HttpRequest.sendPost("http://localhost:6144/Home/RequestPostString", "key=123&v=456");
	
	 private static Logger logger = LoggerFactory.getLogger(HttpRequestUtils.class);    //日志记录
	 
	    /**
	     * httpPost
	     * @param url  路径
	     * @param jsonParam 参数
	     * @return
	     */
	    public static JSONObject httpPost(String url,JSONObject jsonParam){
	        return httpPost(url, jsonParam, false);
	    }
	 
	    /**
	     * post请求
	     * @param url         url地址
	     * @param jsonParam     参数
	     * @param noNeedResponse    不需要返回结果
	     * String s=HttpRequest.sendGet("http://localhost:6144/Home/RequestString", "key=123&v=456");
	     * @return
	     */
	    public static JSONObject httpPost(String url,JSONObject jsonParam, boolean noNeedResponse){
	        //post请求返回结果
	        DefaultHttpClient httpClient = new DefaultHttpClient();
	        JSONObject jsonResult = null;
	        HttpPost method = new HttpPost(url);
	        try {
	            if (null != jsonParam) {
	                //解决中文乱码问题
	                StringEntity entity = new StringEntity(jsonParam.toString(), "utf-8");
	                entity.setContentEncoding("UTF-8");
	                entity.setContentType("application/json");
	                method.setEntity(entity);
	            }
	            HttpResponse result = httpClient.execute(method);
	            url = URLDecoder.decode(url, "UTF-8");
	            /**请求发送成功，并得到响应**/
	            if (result.getStatusLine().getStatusCode() == 200) {
	                String str = "";
	                try {
	                    /**读取服务器返回过来的json字符串数据**/
	                    str = EntityUtils.toString(result.getEntity());
	                    if (noNeedResponse) {
	                        return null;
	                    }
	                    /**把json字符串转换成json对象**/
	                    jsonResult = JSONObject.fromObject(str);
	                } catch (Exception e) {
	                    logger.error("post请求提交失败:" + url, e);
	                }
	            }
	        } catch (IOException e) {
	            logger.error("post请求提交失败:" + url, e);
	        }
	        return jsonResult;
	    }
	 
	 
	    /**
	     * 发送get请求
	     * @param url    路径
	     * String s=HttpRequest.sendGet("http://localhost:6144/Home/RequestString", "key=123&v=456");
	     * @return
	     */
	    public static JSONObject httpGetJSONObject(String url){
	        //get请求返回结果
	        JSONObject jsonResult = null;
	        try {
	            DefaultHttpClient client = new DefaultHttpClient();
	            //发送get请求
	            HttpGet request = new HttpGet(url);
	            HttpResponse response = client.execute(request);
	 
	            /**请求发送成功，并得到响应**/
	            if (response.getStatusLine().getStatusCode() == 200) {
	                /**读取服务器返回过来的json字符串数据**/
	                String strResult = EntityUtils.toString(response.getEntity());
	                /**把json字符串转换成json对象**/
	                jsonResult = JSONObject.fromObject(strResult);
	                url = URLDecoder.decode(url, "UTF-8");
	            } else {
	                logger.error("get请求提交失败:" + url);
	            }
	        } catch (IOException e) {
	            logger.error("get请求提交失败:" + url, e);
	        }
	        return jsonResult;
	    }
	    
	    /**
	     * 发送get请求
	     * @param url    路径
	     * String s=HttpRequest.sendGet("http://localhost:6144/Home/RequestString", "key=123&v=456");
	     * @return
	     */
	    public static String httpGet(String url){
	        //get请求返回结果
	    	String result = "";
	        try {
	            DefaultHttpClient client = new DefaultHttpClient();
	            //发送get请求
	            HttpGet request = new HttpGet(url);
	            
	            //设置编码格式
	            request.addHeader("Content-type","application/json; charset=utf-8");
	            request.setHeader("Accept", "application/json");
	            
	            HttpResponse response = client.execute(request);
	 
	            /**请求发送成功，并得到响应**/
	            if (response.getStatusLine().getStatusCode() == 200) {
	                /**读取服务器返回过来的json字符串数据**/
	                 result = EntityUtils.toString(response.getEntity());
	                
	            } else {
	                logger.error("get请求提交失败:" + url);
	            }
	        } catch (IOException e) {
	            logger.error("get请求提交失败:" + url, e);
	        }
	        return result;
	    }
	    
	    
	    /**
	     * 向指定 URL 发送POST方法的请求
	     * 
	     * @param url
	     *            发送请求的 URL
	     * @param param
	     *            请求参数，请求参数应该是 name1=value1&name2=value2 的形式。
	     * @return 所代表远程资源的响应结果
	     */
	    public static String sendPost(String urlPath, String param){
	          String result = "";
	          BufferedReader buff = null;
	          //向别的服务器些数据
	          PrintWriter writer = null;
	          try {
	            URL url = new URL(urlPath);

	             URLConnection conn =url.openConnection();
	                //设定连接的属性
	                conn.setRequestProperty("accept", "*/*");
	                conn.setRequestProperty("conn", "Keep-Alive");
	                conn.setRequestProperty("user-agent",
	                        "Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1;SV1)");

	                // 发送POST请求必须设置如下两行
	                conn.setDoOutput(true);
	                conn.setDoInput(true);

	                //通过 PrintWriter写数据到 服务器中
	                writer = new PrintWriter( conn.getOutputStream());
	                //添加参数
	                writer.print(param);
	                writer.flush();

	                //获取结果
	                //获取结果
	                buff  = new BufferedReader(new InputStreamReader(conn.getInputStream()));
	                //设定结果
	               String line  = null;
	                while((line = buff.readLine())!= null){
	                    result +=line;
	                }
	                return result;
	        } catch (Exception e) {
	            throw new RuntimeException(e.getMessage());
	        }finally{
	            try {
	                if(writer != null){
	                    writer.close();
	                }

	                if(buff != null){
	                    buff.close();
	                }
	            } catch (Exception e1) {
	                // TODO Auto-generated catch block
	                e1.printStackTrace();
	            }
	        }
	    }
}
